var MAC = {

    listValues: function(name) {

        var list = "";
        var sep = "";

        $(name).each(function(){
            list = list + sep + $(this).val();
            sep = ",";
        });

        return list;

    },

    recordAddEvent: function()
    {
        $("input[name='selectedAddons']:checked").each(function(){

            var id = $(this).val();
            var addonProductPackageName =  $("#addonProductPackageName-" + id).val();
            pageTracker._trackEvent('Order form addon ADD', addonProductPackageName);
        });
    },

    addItem: function(link, params) {

        $("#addbutton").attr("disabled", true);
        $("#addbutton").val("Adding to cart...");

        $.post(link , params,
                function(data){

                    var result = $('response',data).attr('result');

                    if (result == "success")
                    {
                        MAC.recordAddEvent();
                        window.location = $('response',data).attr('action');
                    }
                    else
                    {
                        MAC.renderErrors(data);

                        $("#addbutton").attr("disabled", false);
                        $("#addbutton").html("Add to cart");
                    }
              });
    },

    renderErrors: function(data) {

        var head = '<p class="error-message">' + $('response',data).attr('message') + '</p>';

        var html = '';

        $("#errorBox").hide();
        $(".errorMessage").remove();
        $(".error").removeClass("error");
        $(".submit-button").removeClass('disabled-button');

        $(".form-box").addClass("error-found");

        $('errorinfo',data).each(function(){
            var fieldName = $(this).attr("field");
            var errorMessage = $("body", this).text();

            fieldName = fieldName.replace(".","\\.");

            if ($("#" + fieldName).length > 0 && !fieldName.match('selectedOrderable'))
            {                
                $("#" + fieldName).addClass("error");

                if ($("#" + fieldName).prev().attr("tagName") == "LABEL")
                {
                    $("#" + fieldName).prev().before("<p id='" + fieldName + "-error' class='errorMessage'>" + errorMessage + "</p>");
                }
                else
                {
                    $("#" + fieldName).before("<p id='" + fieldName + "-error' class='errorMessage'>" + errorMessage + "</p>");
                }
            }
            else
            {
                html += '<p class="error-message">' + errorMessage + '</p>';
            }
        });

        if (html == '')
        {
            html = head;
        }
        
        $("#errorBox").html(html);
        $("#errorBox").show();
        MAC.smoothAnchorJump('.form-box-top', 200);
    },

    updateItemTotal: function(url, params) {

        $.get(url, params,
                function(data){

                    $('renewItem',data).each(function(){

                        var months = $(this).attr("maintenanceMonths");
                        var price = $(this).attr("price");

                        $("#maintenanceMonthsPrice-" + months).html("[" + price +"]");
                    });

                    var totalPrice = $('total',data).attr("totalPrice");
                    var totalDiscount = $('total',data).attr("totalDiscount");
                    var discounted = $('total',data).attr("discounted");
                    var extraCartDiscount = $('total',data).attr("extraCartDiscount");
                    var cartDiscounted = $('total',data).attr("cartDiscounted");

                    $('.totalPrice').html(totalPrice);
                    $('.cartdiscount').html(extraCartDiscount);
                    $('[class="totalDiscount"]').html(totalDiscount);

                    if (discounted == "true")
                    {
                        $('[class="discounted"]').show();
                    }
                    else
                    {
                        $('[class="discounted"]').hide();
                    }

                    if (cartDiscounted == "true")
                    {
                        $('[class="discount-text"]').show();
                    }
                    else
                    {
                        $('[class="discount-text"]').hide();
                    }
              });

    },

    manualProductList: function(url, licenseTypeId, orderableItemAction)
    {                
        $("#existingeditionSection").hide();
        $("#existingnodeSection").hide();
        $("#neweditionSection").hide();
        $("#newnodeSection").hide();
        $("#maintenanceSection").hide();
        $("#senErrorSection").hide();

        $.get(url, {licenseTypeId:licenseTypeId, orderableItemAction:orderableItemAction},
                function(data){

                    var result = $('response',data).attr('result');
                    var html = "";


                    if (result == "success")
                    {
                        $('productPackage',data).each(function(){

                            var id = $(this).attr("id");
                            var description = $(this).attr("description");

                            html += "<label>";
                            html += "<input type='radio' value='" + id + "' name='productPackageId' onclick='loadExistingEditions();'><strong>";
                            html += description;
                            html += "</strong></label>";
                        });
                    }

                    $("#productList").html(html);

                    if (html != "")
                    {
                        $("#productSection").show();
                        MAC.checkSenInputs();
                        MAC.smoothAnchorJump('.form-section:visible:last', 2000);
                        
                    }
                    else
                    {
                        $("#productSection").hide();
                    }

              });

    },

    manualexistingeditionlist: function(url, licenseTypeId, productPackageId, orderableItemAction)
    {
        $("#existingnodeSection").hide();
        $("#neweditionSection").hide();
        $("#newnodeSection").hide();
        $("#maintenanceSection").hide();
        $("#senErrorSection").hide();
        $(".error-found").removeClass("error-found");

        $.get(url, {licenseTypeId:licenseTypeId, productPackageId:productPackageId, orderableItemAction:orderableItemAction},
                function(data){

                    var result = $('response',data).attr('result');
                    var html = "";


                    if (result == "success")
                    {
                        $('productedition',data).each(function(){

                            var id = $(this).attr("id");
                            var description = $(this).attr("description");

                            html += "<label>";
                            html += "<input type='radio' value='" + id + "' name='existingProductEditionId' onclick='loadExistingNodes();'><strong>";
                            html += description;
                            html += "</strong></label>";
                        });
                    }

                    $("#existingeditionList").html(html);

                    if (html != "")
                    {
                        $("#existingeditionSection").show();
                        MAC.checkSenInputs();
                        MAC.smoothAnchorJump('.form-section:visible:last');
                    }
                    else
                    {
                        $("#existingeditionSection").hide();
                    }

              });

    },

    manualexistingnodelist: function(url, licenseTypeId, existingProductEditionId)
    {
        $("#neweditionSection").hide();
        $("#newnodeSection").hide();
        $("#maintenanceSection").hide();
        $("#senErrorSection").hide();
        $(".error-found").removeClass("error-found");

        $.get(url, {licenseTypeId:licenseTypeId, existingProductEditionId:existingProductEditionId},
                function(data){

                    var result = $('response',data).attr('result');
                    var noded = $('response',data).attr('noded');

                    var html = "";

                    if (result == "success")
                    {
                        var checked = false;

                        $('additionalnode',data).each(function(){

                            var totalNodes = $(this).attr("totalNodes");
                            var description = $(this).attr("description");

                            html += "<label>";
                            html += "<input type='radio' value='" + totalNodes + "' name='existingNodes' onclick='loadNewEditions();'";
                            if (!checked)
                            {
                                html += " checked ";
                                checked = true;
                            }
                            html += "><strong>";
                            html += description;
                            html += "</strong>";

                            html += "</label>";
                        });
                    }

                    $("#existingnodeList").html(html);

                    if (noded == "true")
                    {
                        $("#existingnodeSection").show();
                        MAC.checkSenInputs();
                        //MAC.smoothAnchorJump('.form-section:visible:last');
                    }
                    else
                    {
                        $("#existingnodeSection").hide();
                    }

                    loadNewEditions();

              });

    },

    manualorderableitemlist: function(url, licenseTypeId, existingProductEditionId, orderableItemAction, existingNodes)
    {
        $("#newnodeSection").hide();
        $("#maintenanceSection").hide();
        $("#senErrorSection").hide();
        $(".error-found").removeClass("error-found");

        $.get(url, {licenseTypeId:licenseTypeId, existingProductEditionId:existingProductEditionId, orderableItemAction:orderableItemAction, existingNodes:existingNodes},
                function(data){

                    var result = $('response',data).attr('result');
                    var html = "";


                    if (result == "success")
                    {
                        var size = $('orderableitem', data).size();

                        $('orderableitem',data).each(function(){

                            var id = $(this).attr("id");
                            var description = $(this).attr("description");
                            var amount = $(this).attr("amount");

                            html += "<label>";
                            html += "<input type='radio' value='" + id + "' name='orderableItemId' onclick='loadNewNodes();'";
                            if (size == 1)
                            {
                                html += " checked "
                            }
                            html += "><strong>";
                            html += description;
                            html += "</strong>";

                            if (amount != "")
                            {
                                html += " [";
                                html += amount;
                                html += "]";
                            }

                            html += "</label>";
                        });

                        if (size == 0)
                        {
                            html += "<label>None Available</label>"
                        }
                    }

                    $("#neweditionList").html(html);

                    if (size <= 1 && orderableItemAction == "renew")
                    {
                        $("#neweditionSection").hide();
                    }
                    else
                    {
                        $("#neweditionSection").show();
                        MAC.checkSenInputs();
                        //MAC.smoothAnchorJump('.form-section:visible:last');
                    }

                    loadNewNodes();

              });

    },

    manualnewnodelist: function(url, orderableItemId, existingNodes)
    {
        $("#maintenanceSection").hide();
        $("#senErrorSection").hide();
        $(".error-found").removeClass("error-found");

        $.get(url, {orderableItemId:orderableItemId, existingNodes:existingNodes},
                function(data){

                    var result = $('response',data).attr('result');
                    var noded = $('response',data).attr('noded');

                    var html = "";
                    var show = false;

                    if (result == "success")
                    {
                        var checked = false;

                        show = (noded == "true" && $('additionalnode',data).size() > 1 || existingNodes != "0");

                        $('additionalnode',data).each(function(){

                            var totalNodes = $(this).attr("totalNodes");
                            var description = $(this).attr("description");

                            if (totalNodes == "-1")
                            {
                                html = "<label>";
                                html += description;
                                html += "</label>";
                                show = true;
                            }
                            else
                            {
                                html += "<label>";
                                html += "<input type='radio' value='" + totalNodes + "' name='newNodes' onclick='loadMaintenance();'";
                                if (!checked)
                                {
                                    html += " checked ";
                                    checked = true;
                                }
                                html += "><strong>";
                                html += description;
                                html += "</strong>";

                                html += "</label>";
                            }
                        });
                    }


                    $("#newnodeList").html(html);

                    if (show)
                    {
                        $("#newnodeSection").show();
                        MAC.checkSenInputs();
                        //MAC.smoothAnchorJump('.form-section:visible:last');
                    }
                    else
                    {
                        $("#newnodeSection").hide();
                    }

                    loadMaintenance();

              });

    },

    manualmaintenancelist: function(url, orderableItemId, existingNodes, newNodes)
    {
        $("#senErrorSection").hide();
        $(".error-found").removeClass("error-found");

        $.get(url, {orderableItemId:orderableItemId, existingNodes:existingNodes, newNodes:newNodes},
                function(data){

                    var result = $('response',data).attr('result');
                    var html = "";

                    var checked = false;

                    if (result == "success")
                    {
                        $('maintenance',data).each(function(){

                            var months = $(this).attr("months");
                            var amount = $(this).attr("amount");

                            html += "<label>";
                            html += "<input type='radio' value='" + months + "' name='maintenanceMonths'";
                            if (!checked)
                            {
                                html += " checked ";
                                checked = true;
                            }
                            html += "><strong>";
                            html += months;
                            html += " months";
                            html += "</strong>";
                            html += " [";
                            html += amount;
                            html += "]";
                            html += "</label>";
                        });
                    }

                    $("#maintenanceList").html(html);

                    if (html != "")
                    {
                        $("#maintenanceSection").show();
                        MAC.checkSenInputs();
                        //MAC.smoothAnchorJump('.form-section:visible:last');
                    }
                    else
                    {
                        $("#maintenanceSection").hide();
                    }

              });

    },

    tablenewnodelist: function(url, accountId, orderableItemId, existingNodes)
    {
        $("#newNodes-" + accountId).hide();
        $("#maintenanceMonths-" + accountId).hide();

        if (orderableItemId != 0)
        {
            $.get(url, {orderableItemId:orderableItemId, existingNodes:existingNodes},
                    function(data){

                        var result = $('response',data).attr('result');
                        var noded = $('response',data).attr('noded');

                        var html = "";
                        var show = false;

                        if (result == "success")
                        {
                            show = (noded == "true" && $('additionalnode',data).size() > 1)

                            $('additionalnode',data).each(function(){

                                var totalNodes = $(this).attr("totalNodes");
                                var description = $(this).attr("description");

                                if (totalNodes == "-1")
                                {
                                    show = true;
                                }

                                html += "<option value='" + totalNodes + "'>" + description + "</option>";

                            });
                        }

                        $("#newNodes-" + accountId).html(html);

                        if (show)
                        {
                            $("#newNodes-" + accountId).show();
                        }

                        loadMaintenanceMonthsForAccount(accountId);

                  });
        }
    },

    tablemaintenancelist: function(url, accountId, orderableItemId, existingNodes, newNodes, skipScroll)
    {
        if (orderableItemId == 0)
        {
            $("#maintenanceMonths-" + accountId).hide();
        }
        else
        {
            $.get(url, {orderableItemId:orderableItemId, existingNodes:existingNodes, newNodes:newNodes, accountId:accountId},
                function(data){

                    var result = $('response',data).attr('result');
                    var html = "";

                    if (result == "success")
                    {
                        $('maintenance',data).each(function()
                        {
                            var months = $(this).attr("months");
                            var amount = $(this).attr("amount");
                            var description = $(this).attr("description");

                            if (description == null) description = months + " months maintenance ";

                            html += "<option value='" + months + "'>" + description + " [" + amount + "]</option>";
                            MAC.checkSenInputs();
                            if(!skipScroll){
                                MAC.smoothAnchorJump('.form-section:visible:last');    
                            }

                        });
                    }
                    else
                    {
                        html = "<option value='0'>Can not be renewed</option>"
                    }

                    $("#maintenanceMonths-" + accountId).html(html);
                    $("#maintenanceMonths-" + accountId).show();
              });

        }
    },   

    manualvalidateorderableitem: function(url, orderableItemId, accountId, emailaddress, existingNodes)
    {
        $.post(url, {accountId:accountId, emailaddress:emailaddress, orderableItemId:orderableItemId, existingNodes:existingNodes},
            function(data){

                var result = $('response',data).attr('result');

                if (result == "success")
                {
                    addManualItem();
                    MAC.checkSenInputs();
                    MAC.smoothAnchorJump('.form-section:visible:last');
                }
                else
                {
                    $("#senValidation").addClass("error-found");
                    $("#senErrorSection").show();
                    MAC.smoothAnchorJump('#senValidation .form-box-top', 200);
                    


                }
          });

    },

    addexistingitems: function(url, elements, skipScroll)
    {
        if (elements.length == 0)
        {
            window.location = url;
        }
        else
        {
            var element = elements.pop();
            var accountId = element["accountId"];
            var orderableItemId = element["orderableItemId"];
            var existingNodes = element["existingNodes"];
            var newNodes = element["newNodes"];
            var maintenanceMonths = element["maintenanceMonths"];
            var emailaddress = element["emailaddress"];
            
            $.post(url, {accountId:accountId, emailaddress:emailaddress, orderableItemId:orderableItemId, existingNodes:existingNodes, newNodes:newNodes, maintenanceMonths:maintenanceMonths},
                function(data){

                    var result = $('response',data).attr('result');

                    if (result == "success")
                    {
                        var action = $('response',data).attr('action');

                        if (elements.length == 0)
                        {
                            url = action;
                        }

                        MAC.addexistingitems(url, elements);
                        MAC.checkSenInputs();
                        if(!skipScroll){
                            MAC.smoothAnchorJump('.form-section:visible:last');    
                        }

                    }
                    else
                    {
                        MAC.renderErrors(data);
                    }
              });

        }

    },

    addexistingitem: function(url, orderableItemId, maintenanceMonths, accountId, emailaddress, existingNodes, newNodes, skipScroll)
    {
        $.post(url, {accountId:accountId, emailaddress:emailaddress, orderableItemId:orderableItemId, existingNodes:existingNodes, newNodes:newNodes, maintenanceMonths:maintenanceMonths},
            function(data){

                var result = $('response',data).attr('result');

                if (result == "success")
                {
                    window.location = $('response',data).attr('action');
                }
                else
                {
                    MAC.renderErrors(data);
                }
          });
        MAC.checkSenInputs();
        if(!(skipScroll)){
            MAC.smoothAnchorJump('.form-section:visible:last');
        }

    },

    checkSenInputs: function() {
    //List all possible divs
    //if they are visible,
    //check to see if the inputs are checked
    //if at least one is checked, enable submit button

              var showButtonArray = [];

                  var visibleRadioSections = $('.form-section:visible').not('.first');
        
                    visibleRadioSections.each(function(i){

                        if(($(this).find('input[type="radio"]').is(':checked')) || $(this).find('input').length === 0){

                            showButtonArray.push(true);

                        } else {
                            showButtonArray.push(false);
                        }

                    });





                  if($.inArray( false, showButtonArray ) === -1){
                    $('#validateSEN').removeClass('disabled-button');
                  } else {
                    $('#validateSEN').addClass('disabled-button');                      
                  }
   },



    renderCart: function (url, checkOpenOrders) {

        $("#cartheader").hide();
        $("#cartbody").empty();
        var blankRow = "<tr>";
        blankRow += "<td colspan='4' style='text-align:center'>";
        blankRow += "<strong>Please wait while we build your cart...</strong>";
        blankRow += "</td>";
        blankRow += "</tr>";

        $("#cartbody").append(blankRow);
        $(".submit-button").hide();

        $.get(url, {checkOpenOrders:checkOpenOrders},
            function(data){

            var result = $('response',data).attr('result');

            if (result == "success")
            {
                $("#cartbody").empty();

                if ($('empty',data).length > 0)
                {
                    $("#cartheader").hide();

                    var blankRow = "<tr>";
                    blankRow += "<td colspan='4' style='text-align:center'>";
                    blankRow += $('empty', data).text();
                    blankRow += "</td>";
                    blankRow += "</tr>";

                    $("#cartbody").append(blankRow);
                    $(".submit-button").hide();
                }
                else
                {
                    $("#cartheader").show();

                    var allOpenOrders = "";

                    var containsDiscount = ($("subtotal",data).attr("discount") != "$0.00")

                    $('lineitem',data).each(function(){

                        var number = $(this).attr("number");
                        var description = $(this).attr("description");
                        var openOrders = $(this).attr("openOrders");
                        var duplicableItem = $(this).attr("duplicableItem");
                        allOpenOrders += openOrders;

                        var row = "<tr>";
                        row += "<td>";
                        if (openOrders != '') row += "<span style='color: #c80909'>";
                        row += "<strong>" + description + "</strong>";
                        if (openOrders != '') row += "</span>";
                        row += " <span class='edit-order'><a href='#' onclick='removeLineItem(" + number + ");'>Remove</a>";
                        if (duplicableItem == "true")
                        {
                            row += " <a href='#' onclick='duplicateLineItem(" + number + ");'>Duplicate</a>";
                        }
                        row += "</span>";

                        var accountname = $(this).find('accountname');

                        if ($(accountname).attr('text') != '')
                        {
                            row += "<br>" + $(accountname).attr('text');
                        }

                        var maintenanceperiod = $(this).find("maintenanceperiod");

                        if ($(maintenanceperiod).attr('text') != '')
                        {
                            row += "<br><strong>" + $(maintenanceperiod).attr('text') + "</strong>";
                        }

                        var nodes = $(this).find("nodes");

                        if ($(nodes).attr('text') != '')
                        {
                            row += "<br>" + $(nodes).attr('text');
                        }

                        var hostedadmindetails = $(this).find("hostedadmindetails");

                        if ($(hostedadmindetails).attr('text') != '')
                        {
                            row += "<br>" + $(hostedadmindetails).attr('text');
                        }

                        var additionalnotes = $(this).find('additionalnotes');

                        if ($(additionalnotes).find('additionalnoteitem').length > 0)
                        {
                            row += "<br>" + $(additionalnotes).attr('text');

                            row += "<ul>";

                            $(additionalnotes).find('additionalnoteitem').each(function(){
                                row += "<li>";
                                row += $(this).attr('text');
                                row += "</li>";
                            });

                            row += "</ul>";
                        }

                        var includes = $(this).find('includes');

                        if ($(includes).find('includesitem').length > 0)
                        {
                            row += "<br>" + $(includes).attr('text');

                            row += "<ul>";

                            $(includes).find('includesitem').each(function(){
                                row += "<li>";
                                row += $(this).attr('text');
                                row += "</li>";
                            });

                            row += "</ul>";
                        }

                        row += "</td>";
                        row += "<td class='discount' style='display:none'>";
                        row += $(this).attr("price");
                        row += "</td>";
                        row += "<td class='discount' style='display:none'>";
                        row += $(this).attr("discount");
                        row += "</td>";
                        row += "<td>";
                        row += $(this).attr("total");
                        row += "</td>";
                        row += "</tr>";

                        $("#cartbody").append(row);

                    });

                    if (allOpenOrders != '')
                    {
                        $(".form-box").addClass("error-found");
                        $("#errorBox").show();
                    }
                    else
                    {
                        $("#errorBox").hide();
                        $(".error-found").removeClass("error-found");
                    }

                    $(".submit-button").show();

                    if (containsDiscount)
                    {
                        var subtotalRow = "<tr class='subtotal'>";
                        subtotalRow += "<td class='subtotal-heading'>";
                        subtotalRow += $("subtotal",data).attr("text");
                        subtotalRow += "</td>";
                        subtotalRow += "<td>";
                        subtotalRow += $("subtotal",data).attr("price");
                        subtotalRow += "</td>";
                        subtotalRow += "<td>";
                        subtotalRow += $("subtotal",data).attr("discount");
                        subtotalRow += "</td>";
                        subtotalRow += "<td>";
                        subtotalRow += $("subtotal",data).attr("total");
                        subtotalRow += "</td>";
                        subtotalRow += "</tr>";

                        $("#cartbody").append(subtotalRow);
                    }

                    if ($("tax",data).attr("tax") == "true")
                    {
                        var taxRow = "<tr class='tax'>";
                        taxRow += "<td class='tax-heading'>";
                        taxRow += $("tax",data).attr("text");
                        taxRow += "</td>";
                        taxRow += "<td class='discount' style='display:none'>&nbsp;</td>";
                        taxRow += "<td class='discount' style='display:none'>&nbsp;</td>";
                        taxRow += "<td>";
                        taxRow += $("tax",data).attr("amount");
                        taxRow += "</td>";
                        taxRow += "</tr>";

                        $("#cartbody").append(taxRow);
                    }

                    var totalRow = "<tr class='total'>";
                    totalRow += "<td class='total-heading'>";
                    totalRow += $("total",data).attr("text");
                    totalRow += "</td>";
                    totalRow += "<td class='discount' style='display:none'>&nbsp;</td>";
                    totalRow += "<td class='discount' style='display:none'>&nbsp;</td>";
                    totalRow +=  "<td class='total-cost'>";
                    totalRow += $("total",data).attr("amount");
                    totalRow += "</td>";
                    totalRow += "</tr>";

                    $("#cartbody").append(totalRow);

                    if (containsDiscount)
                    {
                        $(".discount").show();
                    }
                    else
                    {
                        $(".discount").hide();
                    }
                }
            }
      });
    },


    contentSwitcher: function(settings){
        if  (!settings) {
            var settings = {
			contentClass : '.inner-tab-content',
			navigationId : '#inner-tabs'
        };
        }

              var activeContent = location.hash.split("#")[1]; //'#' + tabName;

                // we will only accept three hashes (to prevent XSS)
                if (activeContent != null && activeContent != '' &&  activeContent != 'neworder' && activeContent != 'renew' && activeContent != 'upgrade') return;

                if (settings.permalinkable === false) {
					$(settings.contentClass).not(':first').hide();
			        $(settings.navigationId).find('li:first').addClass('on');
                } else if (!(activeContent)) {
					$(settings.contentClass).not(':first').hide();
			        $(settings.navigationId).find('li:first').addClass('on');
				} else {
					$(settings.contentClass).not($(location.hash)).hide();
					var navItems = $(settings.navigationId).find('a');

					navItems.each(function(i){
                        $(this).parent('li').removeClass('on');
						if (('#' + $(this).attr('href').split('tab=')[1]) === location.hash) {
							$(this).parent('li').addClass('on');
						}
					});
					showMe(activeContent);
				}




		        //onClick set the active state, hide the content panels and show the correct one
		        $(settings.navigationId).find('a').click(function(e){
                    e.preventDefault();

		            var contentToShow = $(this).attr('href').split('tab=')[1];


		            //dissable normal link behaviour

		            //set the proper active class for active state css
		            $(settings.navigationId).find('li').removeClass('on');
		            $(this).parent('li').addClass('on');

                    if(settings.permalinkable === true){

                        location.hash = contentToShow;
                    }

					showMe(contentToShow);
		        });

				function showMe(el){
					el = $("#content-" + el);
					$(settings.contentClass).hide();
					el.show();
				}
    },

	disableContactInputs: function(formSection, clearInput){
		disablerCheckBox = $(formSection).find("input[type='checkbox']:first");

		      if(disablerCheckBox.attr("checked")){
		        MAC.disableFields(formSection);
		      } else {
		        MAC.enableFields(formSection, clearInput);
		      }

		      disablerCheckBox.click(function(){
		        if($(this).attr("checked")){
    		           MAC.disableFields(formSection);
		        } else {
		            MAC.enableFields(formSection, clearInput);
		        }
		      });


	},

    enableFields: function(formSection, clearInput) {
        $(formSection).removeClass('disabled-form');
        $(formSection).find("label").css('color', '#404040');
        $(formSection).find(".required").css('visibility', 'visible');
        $(formSection).find("input[type='text']").attr({'disabled': ''}).css('color', '#404040');
        if (clearInput) $(formSection).find("input[type='text']").val('');
    },

    disableFields: function(formSection) {
                  $(formSection).addClass('disabled-form');
		          $(formSection).find("label").not(':first').css('color', '#ccc');
		          $(formSection).find(".required").css('visibility', 'hidden');
		          $(formSection).find("input[type='text']").attr('disabled', 'disabled');
                  $(formSection).find("input[type='text']").css('color', '#fff');
    },

    smoothAnchorJump: function(anchorName, speed) {
        anchorName = $(anchorName);

	    var target_offset = anchorName.offset();
	    var target_top = target_offset.top;

        if (!speed) {
            var speed = 1000;
        }

	    //goto that anchor by setting the body scroll top to anchor top
	    $('html, body').animate({scrollTop:target_top}, speed);
    },



    initPopups:function() {
       $('a[rel^="popup"]').click(function() {

           var is_chrome = navigator.userAgent.toLowerCase().indexOf('chrome') > -1;
           var width, height;

           if(is_chrome) {
               width= 657;
               height= 473;
           } else {
               width = 655;
               height = 410
           }


           var rel = $(this).attr('rel');
           if (rel.indexOf('[') != -1) {
               width = +rel.substring(rel.indexOf('[') + 1, rel.indexOf(',')) || width;
               height = +rel.substring(rel.indexOf(',') + 1, rel.indexOf(']')) || height;
           }
           MAC.popUp(this.href, width, height);
           return false;
       });
   },


    popUp: function (url, width, height) {
                width = width ? width : 830;
                height = height ? height : 680;
                var newwindow = window.open(url, 'name', 'toolbar=0,scrollbars=0,location=0,statusbar=0, menubar=0,resizable=0,width=' + width + ',height=' + height);
                if (window.focus) {
                    newwindow.focus()
                }
    }

};





function simpleHover(target, el, another_class){
	$(target).hover(
		function(){


			if(another_class){
				$(this).parents(el).addClass(another_class + '-hover');
			}else {
			$(this).parents(el).addClass('hover');
			}
		},
		function(){
			if(another_class){

				$(this).parents(el).removeClass(another_class + '-hover');

					}else {
			$(this).parents(el).removeClass('hover');
					}
		}
	);
}


function hideShowInputAction(hiddenEl, actionEl, showOnLoad){

	if(!(showOnLoad === 'show')) {
		$(hiddenEl).hide();
		$(actionEl).click(function(){
			if ($(actionEl+':checked').length) {
				$(hiddenEl).slideDown('fast');
			} else {
				$(hiddenEl).slideUp('fast');
			}
		});
	} else {
		$(actionEl).click(function(){
			if ($(actionEl+':checked').length) {
				$(hiddenEl).slideUp('fast');
			} else {
				$(hiddenEl).slideDown('fast');
			}
		});
	}
}


function addMoreContacts() {

			var count = 1;
			$('.first-secondary-contact .column input[type=radio]').eq(0).attr('checked', true);
			$('.first-secondary-contact .last input[type=radio]').eq(0).attr('checked', true);

			$('.add-another-contact').live('click', function(e){
				e.preventDefault();
					count ++;

					$('.additional-contact:last input[type=input]').each(function(i){
						$(this).attr('value', '');
					});

					$('.in-queue input').each(function(i){
						var thisId = $(this).attr('id');
						var thisName = $(this).attr('name');

						$(this).attr('id', (thisId + "-form-" + count));
						$(this).attr('name', (thisName + "-form-" + count));
					});

					$('.prototype').clone().insertAfter('.additional-contact:last').removeClass('prototype').addClass('clone');

					$('.in-queue').removeClass('in-queue').addClass('current');

					$('.clone').removeClass('clone').addClass('in-queue');

					$('.additional-contact').filter('.current').slideDown('slow', function(){
						// window.location.hash = "active-form";
						$('.current:last input[type=text]').eq(0).focus();
						$('.current:last input[type=radio]').eq(0).attr('checked', true);
						$('.current:last .last input[type=radio]').eq(0).attr('checked', true);

					});

					$(this).animate({"opacity": "0"}, "fast", function(){
						$(this).css({'display': 'none'});
					});

			});
}
